package com.hondee.fuzzyquery.entity.access.querycondition;

import java.util.Iterator;
import java.util.List;

import com.hondee.fuzzyquery.entity.access.IQueryCondition;

public class SqlQueryCondition implements IQueryCondition {
	
	private Logic sublogic;
	private SqlWhereConditionEnum where;
	private String field;
	private Object param1;
	private Object param2;
	
	private List<IQueryCondition> subQueryConditions;
	
	public SqlQueryCondition(Logic sublogic, List<IQueryCondition> subQueryConditions) {
		this.sublogic = sublogic;
		this.subQueryConditions = subQueryConditions;
	}
	
	public SqlQueryCondition(Logic sublogic, SqlWhereConditionEnum where,String field, Object param1) {
		this.sublogic = sublogic;
		this.where = where;
		this.field = field;
		this.param1 = param1;
	}
	public SqlQueryCondition(Logic sublogic, SqlWhereConditionEnum where,String field, Object param1, Object param2) {
		this.sublogic = sublogic;
		this.where = where;
		this.field = field;
		this.param1 = param1;
		this.param2 = param2;
	}
	public SqlQueryCondition(Logic sublogic, SqlWhereConditionEnum where,String field, Object param1, Object param2,
			List<IQueryCondition> subQueryConditions) {
		this.sublogic = sublogic;
		this.where = where;
		this.field = field;
		this.param1 = param1;
		this.param2 = param2;
		this.subQueryConditions = subQueryConditions;
	}
	
	public String toString(){
		
		StringBuilder wherestr = new StringBuilder();
		String localCondition = SqlWhereStringBuilder.build(field, where, param1, param2);
		if(!localCondition.equals("")){
			wherestr.append(localCondition);
		}
		String logicStr = SqlWhereLogicStringBuilder.get(sublogic);
		if(subQueryConditions!=null && subQueryConditions.size()>0 && sublogic != Logic.NONE){
			if(wherestr.length()>0){
				wherestr.append(logicStr);
			}
			wherestr.append("(");
			Iterator<IQueryCondition> iterator = subQueryConditions.iterator();
			while(iterator.hasNext()){
				wherestr.append(iterator.next());
				if(iterator.hasNext()){
					wherestr.append(logicStr);
				}
			}
			wherestr.append(")");
		}
		return wherestr.toString();
	}
}
